package com.alipay.sofa.award.endpoint.filter;

import com.alipay.sofa.award.endpoint.holder.LocaleHolder;

import javax.ws.rs.container.*;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * RequestLanguageFilter
 *
 * @author yangguanchao
 * @since 2018/08/27
 */
@Provider
@PreMatching
public class RequestLanguageFilter implements ContainerRequestFilter, ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        //Accept-Language = zh-CN,zh;q=0.9,en;q=0.8
        List<Locale> localeList = requestContext.getAcceptableLanguages();
        if (localeList != null && localeList.size() > 0) {
            //Accept Language
            LocaleHolder.setLocale(localeList.get(0));
        }
    }

    @Override
    public void filter(ContainerRequestContext requestContext,
                       ContainerResponseContext responseContext) throws IOException {
        LocaleHolder.remove();
    }
}
